namespace CIS.Customer
{
    using CISLib;
    using System;
    using System.Data;
    using System.IO;
    using System.Text;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    public class CustomerInfoListPage : Page
    {
        protected DataGrid customerListDg;
        protected Image iBtnCustomer;
        protected LinkButton lkbDown;
        protected Button newUserBtn;
        protected UserPrincipal Principal = null;
        protected Button searchBtn;

        private void customerListDg_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            string cmd = e.CommandName;
            string strCustomerId = e.CommandArgument.ToString();
            switch (cmd)
            {
                case "Edit":
                    base.Response.Redirect("~/Customer/CustomerBasicInfoPage.aspx?IsModify=True&CustomerId=" + strCustomerId, true);
                    break;

                case "delete":
                    if ((this.Principal.SysUser.IsAdmin <= 0) && !ManageSystemConfig.IsThisCustomerMaster(this.Principal.SysUser.UserId, new Guid(strCustomerId)))
                    {
                        base.Response.Write("<script> alert('没有权限操作！') </script>");
                    }
                    else
                    {
                        string customerName = ManageCustomer.GetCustomerBasicInfoViaId(new Guid(strCustomerId)).Name;
                        ManageCustomer.RemoveCustomerViaId(new Guid(strCustomerId));
                        ManageLog.InsertLog(this.Principal.SysUser.UserId, this.Principal.SysUser.LoginName, DateTime.Now, "RemoveCustomer", "IP:" + base.Request.UserHostAddress + " DNS:" + base.Request.UserHostName, customerName);
                        if ((this.customerListDg.Items.Count == 1) && (this.customerListDg.CurrentPageIndex > 0))
                        {
                            this.customerListDg.CurrentPageIndex--;
                        }
                        this.DgDataBind();
                    }
                    break;
            }
        }

        private void customerListDg_ItemCreated(object sender, DataGridItemEventArgs e)
        {
        }

        private void customerListDg_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
        {
            this.customerListDg.CurrentPageIndex = e.NewPageIndex;
            this.DgDataBind();
        }

        private void DgDataBind()
        {
            if (base.Request.QueryString["IsSearch"] == "True")
            {
                string strCompanyName = this.Page.Session["CompanyName"].ToString();
                string strCustomerName = this.Page.Session["CustomerName"].ToString();
                string strCustomerTitle = this.Page.Session["CustomerTitleTbx"].ToString();
                int iCustomerLevel = Convert.ToInt32(this.Page.Session["CustomerLevel"]);
                string strCoupon = this.Page.Session["Coupon"].ToString();
                string strTravelTool = this.Page.Session["TravelTool"].ToString();
                string strDegree = this.Page.Session["Degree"].ToString();
                string strMajor = this.Page.Session["Major"].ToString();
                string strGraduateSchool = this.Page.Session["GraduateSchool"].ToString();
                string strCompany = this.Page.Session["Company"].ToString();
                string strWorkPlace = this.Page.Session["WorkPlace"].ToString();
                string strHotel = this.Page.Session["Hotel"].ToString();
                string strTour = this.Page.Session["Tour"].ToString();
                string strImageInfo = this.Page.Session["ImageInfo"].ToString();
                string strNewsPaper = this.Page.Session["NewsPaper"].ToString();
                string strEditor = this.Page.Session["Editor"].ToString();
                Guid PrefValueId = new Guid(this.Page.Session["PrefValue"].ToString());
                Guid PrefTypeId = new Guid(this.Page.Session["PrefType"].ToString());
                Guid catId = new Guid(this.Page.Session["CATId"].ToString());
                Guid regionId = new Guid(this.Page.Session["RegionId"].ToString());
                DateTime startDateASBContractSign = (DateTime) this.Page.Session["ASBContractSignStart"];
                DateTime endDateASBContractSign = (DateTime) this.Page.Session["ASBContractSignEnd"];
                DateTime startDateASBContractEffect = (DateTime) this.Page.Session["ASBContractEffectStart"];
                DateTime endDateASBContractEffect = (DateTime) this.Page.Session["ASBContractEffectEnd"];
                DateTime startDateEVMeeting = (DateTime) this.Page.Session["EVMeetingStart"];
                DateTime endDateEVMeeting = (DateTime) this.Page.Session["EVMeetingEnd"];
                DateTime startDateVisitingAbroad = (DateTime) this.Page.Session["VisitingAbroadStart"];
                DateTime endDateVisitingAbroad = (DateTime) this.Page.Session["VisitingAbroadEnd"];
                DateTime startDateASBTraining = (DateTime) this.Page.Session["ASBTrainingStart"];
                DateTime endDateASBTraining = (DateTime) this.Page.Session["ASBTrainingEnd"];
                DateTime startDateASBEvents = (DateTime) this.Page.Session["ASBEventsStart"];
                DateTime endDateASBEvents = (DateTime) this.Page.Session["ASBEventsEnd"];
                DateTime startDateEvents = (DateTime) this.Page.Session["EventsStart"];
                DateTime endDateEvents = (DateTime) this.Page.Session["EventsEnd"];
                DateTime startDateResponsibleStaff = (DateTime) this.Page.Session["ResponsibleStaffStart"];
                DateTime endDateResponsibleStaff = (DateTime) this.Page.Session["ResponsibleStaffEnd"];
                DateTime startDateASBReception = (DateTime) this.Page.Session["ASBReceptionStart"];
                DateTime endDateASBReception = (DateTime) this.Page.Session["ASBReceptionEnd"];
                DateTime startDateCompetitorMeeting = (DateTime) this.Page.Session["CompetitorMeetingStart"];
                DateTime endDateCompetitorMeeting = (DateTime) this.Page.Session["CompetitorMeetingEnd"];
                DateTime startDateCompetitorEvents = (DateTime) this.Page.Session["CompetitorEventsStart"];
                DateTime endDateCompetitorEvents = (DateTime) this.Page.Session["CompetitorEventsEnd"];
                DateTime startDatePic = (DateTime) this.Page.Session["PicStart"];
                DateTime endDatePic = (DateTime) this.Page.Session["PicEnd"];
                try
                {
                    Area[] areaAry = this.Principal.OwnArea;
                    Cat[] catAry = this.Principal.OwnCat;
                    Province[] provinceAry = this.Principal.Province;
                    if ((catId.ToString() != "00000000-0000-0000-0000-000000000000") || (regionId.ToString() != "00000000-0000-0000-0000-000000000000"))
                    {
                        if (catId.ToString() == "00000000-0000-0000-0000-000000000000")
                        {
                            provinceAry = new Province[] { ManageProvince.GetProvinceViaId(regionId) };
                        }
                        else if (regionId.ToString() == "00000000-0000-0000-0000-000000000000")
                        {
                            catAry = new Cat[] { ManageCAT.GetCATViaId(catId) };
                        }
                        else
                        {
                            provinceAry = new Province[] { ManageProvince.GetProvinceViaId(regionId) };
                            catAry = new Cat[] { ManageCAT.GetCATViaId(catId) };
                        }
                    }
                    int areaLen = areaAry.Length;
                    int catLen = catAry.Length;
                    int provinceLen = provinceAry.Length;
                    DataTable dataTable = new DataTable();
                    int i = 0;
                    int j = 0;
                    int x = 0;
                    int y = 0;
                    for (i = 0; i < areaLen; i++)
                    {
                        for (x = 0; x < provinceLen; x++)
                        {
                            for (j = 0; j < catLen; j++)
                            {
                                DataTable dt = ManageCustomer.GetCustomerBasicInfo(areaAry[i].AreaId, catAry[j].CatId, provinceAry[x].ProvinceId, strCompanyName, strCustomerName, strCustomerTitle, iCustomerLevel, strCoupon, strTravelTool, strDegree, strMajor, strGraduateSchool, strCompany, strWorkPlace, startDateASBContractSign, endDateASBContractSign, startDateASBContractEffect, endDateASBContractEffect, startDateEVMeeting, endDateEVMeeting, startDateVisitingAbroad, endDateVisitingAbroad, startDateASBTraining, endDateASBTraining, startDateASBEvents, endDateASBEvents, startDateEvents, endDateEvents, startDateResponsibleStaff, endDateResponsibleStaff, startDateASBReception, endDateASBReception, startDateCompetitorMeeting, endDateCompetitorMeeting, startDateCompetitorEvents, endDateCompetitorEvents, startDatePic, endDatePic, strHotel, strTour, PrefValueId, PrefTypeId, strImageInfo, strNewsPaper, strEditor).Tables[0];
                                if (y == 0)
                                {
                                    dataTable = dt.Clone();
                                    y++;
                                }
                                foreach (DataRow tmpRow in dt.Rows)
                                {
                                    if (this.Principal.OwnRole.IsUnmasterView == 1)
                                    {
                                        dataTable.ImportRow(tmpRow);
                                    }
                                    else if (tmpRow[10].ToString() == this.Principal.SysUser.UserId.ToString())
                                    {
                                        dataTable.ImportRow(tmpRow);
                                    }
                                }
                            }
                        }
                    }
                    this.customerListDg.DataSource = dataTable;
                    this.customerListDg.DataBind();
                }
                catch (Exception)
                {
                }
            }
            else
            {
                Area[] areaAry = this.Principal.OwnArea;
                Cat[] catAry = this.Principal.OwnCat;
                Province[] provinceAry = this.Principal.Province;
                int areaLen = areaAry.Length;
                int catLen = catAry.Length;
                int provinceLen = provinceAry.Length;
                DataTable dataTable = new DataTable();
                int i = 0;
                int j = 0;
                int x = 0;
                int y = 0;
                for (i = 0; i < areaLen; i++)
                {
                    for (x = 0; x < provinceLen; x++)
                    {
                        for (j = 0; j < catLen; j++)
                        {
                            DataTable dt = ManageCustomer.GetCustomerBasicInfo(catAry[j].CatId, provinceAry[x].ProvinceId, areaAry[i].AreaId);
                            if (y == 0)
                            {
                                dataTable = dt.Clone();
                                y++;
                            }
                            foreach (DataRow tmpRow in dt.Rows)
                            {
                                if (this.Principal.OwnRole.IsUnmasterView == 1)
                                {
                                    dataTable.ImportRow(tmpRow);
                                }
                                else if (tmpRow[10].ToString() == this.Principal.SysUser.UserId.ToString())
                                {
                                    dataTable.ImportRow(tmpRow);
                                }
                            }
                        }
                    }
                }
                this.customerListDg.DataSource = dataTable;
                this.customerListDg.DataBind();
            }
        }

        private void FillPage()
        {
            this.DgDataBind();
        }

        protected string GetUserName(object obj)
        {
            return ManageUser.GetUserViaId((Guid) obj).LoginName;
        }

        private void InitializeComponent()
        {
            this.newUserBtn.Click += new EventHandler(this.newUserBtn_Click);
            this.searchBtn.Click += new EventHandler(this.searchBtn_Click);
            this.lkbDown.Click += new EventHandler(this.lkbDown_Click);
            this.customerListDg.ItemCreated += new DataGridItemEventHandler(this.customerListDg_ItemCreated);
            this.customerListDg.ItemCommand += new DataGridCommandEventHandler(this.customerListDg_ItemCommand);
            this.customerListDg.PageIndexChanged += new DataGridPageChangedEventHandler(this.customerListDg_PageIndexChanged);
            base.Load += new EventHandler(this.Page_Load);
        }

        private void InitPage()
        {
            this.SetFrom();
            if (this.Principal.SysUser.IsDownload == 1)
            {
                this.lkbDown.Visible = true;
            }
            else
            {
                this.lkbDown.Visible = false;
            }
            this.customerListDg.PageSize = 14;
        }

        private void lkbDown_Click(object sender, EventArgs e)
        {
            Area[] areaAry = this.Principal.OwnArea;
            Cat[] catAry = this.Principal.OwnCat;
            Province[] provinceAry = this.Principal.Province;
            int areaLen = areaAry.Length;
            int catLen = catAry.Length;
            int provinceLen = provinceAry.Length;
            DataTable dataTable = new DataTable();
            int i = 0;
            int j = 0;
            int x = 0;
            int y = 0;
            for (i = 0; i < areaLen; i++)
            {
                for (j = 0; j < catLen; j++)
                {
                    for (x = 0; x < provinceLen; x++)
                    {
                        DataTable tmpDt = ManageCustomer.GetCustomerBasicInfoDownLoad(catAry[j].CatId, provinceAry[x].ProvinceId, areaAry[i].AreaId);
                        if (y == 0)
                        {
                            dataTable = tmpDt.Clone();
                            y++;
                        }
                        foreach (DataRow tmpRow in tmpDt.Rows)
                        {
                            dataTable.ImportRow(tmpRow);
                        }
                    }
                }
            }
            DataTable dt = dataTable;
            StringWriter sw = new StringWriter();
            for (int ii = 0; ii < dt.Columns.Count; ii++)
            {
                if (ii == (dt.Columns.Count - 1))
                {
                    sw.Write(dt.Columns[ii].ColumnName + "\n");
                }
                else
                {
                    sw.Write(dt.Columns[ii].ColumnName + ",");
                }
            }
            for (int ii = 0; ii < dt.Rows.Count; ii++)
            {
                DataRow dr = dt.Rows[ii];
                for (int jj = 0; jj < dt.Columns.Count; jj++)
                {
                    if (jj == (dt.Columns.Count - 1))
                    {
                        sw.Write(dr[dt.Columns[jj].ColumnName] + "\n");
                    }
                    else
                    {
                        sw.Write(dr[dt.Columns[jj].ColumnName] + ",");
                    }
                }
            }
            sw.Close();
            base.Response.AddHeader("Content-Disposition", "attachment; filename=CustomerInfo" + DateTime.Now.Millisecond.ToString() + ".csv");
            base.Response.ContentType = "application/ms-excel";
            base.Response.ContentEncoding = Encoding.GetEncoding("GB2312");
            base.Response.Write(sw);
            base.Response.End();
        }

        private void newUserBtn_Click(object sender, EventArgs e)
        {
            this.Page.Session.Add("IsModify", "False");
            string strModify = (string) this.Page.Session["IsModify"];
            this.Page.Session.Remove("CustomerId");
            base.Response.Redirect("~/Customer/CustomerBasicInfoPage.aspx?IsModify=" + strModify, true);
        }

        protected override void OnInit(EventArgs e)
        {
            this.InitializeComponent();
            base.OnInit(e);
            this.Principal = this.Context.User as UserPrincipal;
        }

        private void Page_Load(object sender, EventArgs e)
        {
            if (!base.IsPostBack)
            {
                this.SelectAuth();
            }
        }

        private void searchBtn_Click(object sender, EventArgs e)
        {
            base.Response.Redirect("~/Customer/CustomerInfoSearchPage.aspx", true);
        }

        private void SelectAuth()
        {
            if (this.Principal.OwnRole.TypeB == 0)
            {
                this.InitPage();
                this.FillPage();
                this.newUserBtn.Visible = false;
                this.searchBtn.Visible = false;
                this.lkbDown.Visible = false;
            }
            else if (this.Principal.OwnRole.TypeB == 1)
            {
                this.InitPage();
                this.FillPage();
            }
            else if (this.Principal.OwnRole.TypeB == 2)
            {
                this.newUserBtn.Visible = false;
                this.searchBtn.Visible = false;
                this.lkbDown.Visible = false;
            }
        }

        private void SetFrom()
        {
            string language = this.Session["language"].ToString();
            string path = base.Server.MapPath("~/LanguageConfig.xml");
            if (language == "cn")
            {
                this.iBtnCustomer.ImageUrl = "../images/title_customerinfo.jpg";
            }
            else if (language == "en")
            {
                this.iBtnCustomer.ImageUrl = "../images/title_customerinfoEn.jpg";
            }
            this.newUserBtn.Text = ManageSystemConfig.GetSystemSetLanguage("CustomerInfoListPage", "newUserBtn", language, path);
            this.searchBtn.Text = ManageSystemConfig.GetSystemSetLanguage("CustomerInfoListPage", "searchBtn", language, path);
            this.lkbDown.Text = ManageSystemConfig.GetSystemSetLanguage("CustomerInfoListPage", "lkbDown", language, path);
            this.customerListDg.Columns[0].HeaderText = ManageSystemConfig.GetSystemSetLanguage("CustomerInfoListPage", "Name", language, path);
            this.customerListDg.Columns[1].HeaderText = ManageSystemConfig.GetSystemSetLanguage("CustomerInfoListPage", "Title", language, path);
            this.customerListDg.Columns[2].HeaderText = ManageSystemConfig.GetSystemSetLanguage("CustomerInfoListPage", "Company", language, path);
            this.customerListDg.Columns[3].HeaderText = ManageSystemConfig.GetSystemSetLanguage("CustomerInfoListPage", "Gender", language, path);
            this.customerListDg.Columns[4].HeaderText = ManageSystemConfig.GetSystemSetLanguage("CustomerInfoListPage", "Depart", language, path);
            this.customerListDg.Columns[5].HeaderText = ManageSystemConfig.GetSystemSetLanguage("CustomerInfoListPage", "Edit", language, path);
            this.customerListDg.Columns[6].HeaderText = ManageSystemConfig.GetSystemSetLanguage("CustomerInfoListPage", "Delete", language, path);
        }
    }
}

